import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:url_launcher/url_launcher.dart';

//如何打开第三方应用？
void main() {
  runApp(LaunchPage());
}

class LaunchPage extends StatelessWidget {
  // This widget is the root of your application.
  // 此小部件是您的应用程序的根。
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '如何打开第三方应用？',
      theme: ThemeData(
        // This is the theme of your application.
        // 这是您的应用程序的主题。
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        // 尝试使用“ flutter run”运行您的应用程序。 您会看到该应用程序具有一个蓝色的工具栏。 然后，在不退出应用程序的情况下，
        // 尝试将下面的primarySwatch更改为Colors.green，然后调用“ hot reload”（在运行“ flutter run”的控制台中按“ r”，
        // 或者直接在其中保存对“ hot reload”的更改） Flutter IDE）。请注意，计数器并未重置为零； 应用程序未重新启动。
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        // 这使视觉密度适应您在其上运行应用程序的平台。 对于台式机平台，
        // 控件将比移动平台上的控件更小，更靠近（更密集）。
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
//      home: MyHomePage(title: '如何使用Flutter包和插件？'),
      home: Scaffold(
        appBar: AppBar(
          title: Text('如何打开第三方应用？'),
          leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Icon(Icons.arrow_back),
          ),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                onPressed: () => _launchURL(),
                child: Text('打开浏览器'),
              ),
              RaisedButton(
                onPressed: () => _openMap(),
                child: Text('打开地图'),
              ),
              RaisedButton(
                onPressed: () => _openSms,
                child: Text('打开短信'),
              )
            ],
          ),
        ),
      ),
    );
  }

  _launchURL() async {
    const url = 'http://www.devio.org/';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  _openSms() async {
//    final Uri _emailLaunchUri = Uri(
//        scheme: 'mailto',
//        path: 'smith@example.com',
//        queryParameters: {
//          'subject': 'Example Subject & Symbols are allowed!'
//        }
//    );

// ...

// mailto:smith@example.com?subject=Example+Subject+%26+Symbols+are+allowed%21
//    launch(_emailLaunchUri.toString());
    final Uri _emailLaunchUri = Uri(
      scheme: 'sms:17866638932',
    );
    launch(_emailLaunchUri.toString());
  }

  _openMap() async {
    const url = 'geo:52.32,4.917'; // app开发者提供的schema
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      // ios
      const url = 'http://maps.apple.com/?ll=52.32,4.917';
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    }
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.
  //此小部件是您的应用程序的主页。 它是有状态的，
  //表示它具有一个State对象（定义如下），该对象包含
  //影响其外观的字段。

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".
  //此类是状态的配置。 它保存由父级（在此例中为App小部件）
  // 提供并由State的build方法使用的值（在本例中为标题）。
  // Widget子类中的字段始终标记为“最终”。

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      //对该setState的调用告诉Flutter框架此状态有所更改，
      // 这导致它重新运行下面的build方法，以便显示内容可以
      // 反映更新的值。 如果我们在不调用setState（）的情
      // 况下更改_counter，则不会再次调用build方法，
      // 因此似乎什么也没有发生。
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    // 每次调用setState时都会重新运行此方法，例如通过
    // 上面的_incrementCounter方法完成。Flutter框架已进行
    // 了优化，可以快速重新运行构建方法，因此您可以重新
    // 构建任何需要更新的内容，而不必单独更改实例小部件。

    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        //这里，我们从由App.build方法创建的MyHomePage对象
        // 中获取值，并使用它来设置应用栏标题。
        title: Text(widget.title),
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(Icons.arrow_back),
        ),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        // Center是一个布局小部件。 它需要一个孩子并将其放置在父母中间。
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).

          //列也是布局小部件。 它会列出孩子列表并垂直排列。
          // 默认情况下，它会自行调整大小以使其子级水平放置，
          // 并尝试与父级一样高。

          //调用“调试绘画”（在控制台中按“ p”，从Android
          // Studio中的Flutter Inspector中选择“切换调试
          // 绘画”操作，或在Visual Studio Code中选择
          // “切换调试绘画”命令）以查看 每个小部件。

          //列具有各种属性，可控制其自身大小以及如何定位
          // 其子级。 在这里，我们使用mainAxisAlignment
          // 将子项垂直居中； 这里的主轴是垂直轴，因为列
          // 是垂直的（交叉轴是水平的）。

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
              style: TextStyle(color: ColorUtil.color('#899900')),
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
      //这个逗号结尾使构建方法的自动格式化更好。
    );
  }
}
